<template>
    <div class="like-article">
        <!-- attitude的值 -1：默认(未点赞) 0：不喜欢 1：喜欢(点赞) -->
        <van-icon 
            :name="attitude === 1 ? 'good-job' : 'good-job-o'" 
            :color="attitude === 1 ? '#e5645f' : ''" 
            @click="onLike(articleId)"/>
    </div>
</template>

<script>
import {addLike, deleteLike} from '@/api/article'

export default {
    name: 'LikeArticle',
    props: {
        attitude: {
            type: Number,
            required: true
        },
        articleId: {
            type: [Number, String],
            required: true
        }
    },
    methods: {
        async onLike(articleId) {
            try {
                if(this.attitude === 1) {
                    await deleteLike(articleId)
                    this.$toast.success('取消点赞')
                    // 更新点赞状态
                    this.$emit('update:attitude', -1)
                } else {
                    await addLike(articleId)
                    this.$toast.success('点赞成功')
                    // 更新点赞状态
                    this.$emit('update:attitude', 1)
                }
            } catch(err) {
                console.log('操作失败', err)
            }
        }
    }
}
</script>

<style lang="less" scoped>
.van-icon {
    font-size: 40px;
}
</style>